package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-06
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    //登录
    public ResponseResult login(LoginDto dto) {
        //判断参数
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查找用户
        LambdaQueryWrapper<AdUser> qw=new LambdaQueryWrapper<>();
        qw.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(qw);
        if (one==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取用户表中得盐
        String salt = one.getSalt();

        //使用前端传入得密码拼接盐，进行MD5计算得到密码
        String userPassword=dto.getPassword()+ salt;
        String asHex = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        //使用密码和数据表中的密码进行对比
        if (!asHex.equals(one.getPassword())) {
            //不一致报错
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致，使用JWT生成token，将用户id放入到JWT得自定义声明中
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",one.getId());
        String token = AppJwtUtil.getToken(map);
        //给前端返回定义好的格式
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("token",token);
        //隐藏用户敏感信息
        one.setPassword(null);
        one.setSalt(null);
        one.setPhone(null);
        map1.put("user",one);
        return ResponseResult.okResult(map1);
    }
}
